package com.cleaningcloud.erp.service.impl;

import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.UniqueIdUtils;
import com.cleaningcloud.common.security.utils.CommunityTypeConversionUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.domain.ErpCommodityStockAlter;
import com.cleaningcloud.erp.api.domain.ErpWareCommodityNumber;
import com.cleaningcloud.erp.api.utils.StockCommodityAlterUtils;
import com.cleaningcloud.erp.domain.ErpCommodityUnit;
import com.cleaningcloud.erp.domain.ErpWareAllocate;
import com.cleaningcloud.erp.domain.dto.ErpWareAllocateDto;
import com.cleaningcloud.erp.domain.vo.ErpWareAllocateDetailsVo;
import com.cleaningcloud.erp.domain.vo.ErpWareAllocateVo;
import com.cleaningcloud.erp.mapper.ErpCommodityStockAlterMapper;
import com.cleaningcloud.erp.mapper.ErpCommodityUnitMapper;
import com.cleaningcloud.erp.mapper.ErpWareAllocateMapper;
import com.cleaningcloud.erp.mapper.ErpWareCommodityNumberMapper;
import com.cleaningcloud.erp.service.IErpWareAllocateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 调拨Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-10-08
 */
@Service
public class ErpWareAllocateServiceImpl implements IErpWareAllocateService {
    @Autowired
    private ErpWareAllocateMapper erpWareAllocateMapper;
    @Autowired
    private ErpWareCommodityNumberMapper erpWareCommodityNumberMapper;

    @Autowired
    private ErpCommodityStockAlterMapper erpCommodityStockAlterMapper;

    @Autowired
    private ErpCommodityUnitMapper erpCommodityUnitMapper;

    /**
     * 查询调拨
     *
     * @param wareAllocateId 调拨主键
     * @return 调拨
     */
    @Override
    public ErpWareAllocateVo selectErpWareAllocateByWareAllocateId(Long wareAllocateId) {
        ErpWareAllocateVo wareAllocateVo = erpWareAllocateMapper.selectErpWareAllocateByWareAllocateId(wareAllocateId);
        for (ErpWareAllocateDetailsVo erpWareAllocateDetailsVo : wareAllocateVo.getDetailsList()) {
            erpWareAllocateDetailsVo.setCommodityType(CommunityTypeConversionUtils.conversion(erpWareAllocateDetailsVo.getCommodityType()));
            ErpCommodityUnit query = new ErpCommodityUnit();
            query.setCommodityId(erpWareAllocateDetailsVo.getCommodityId());
            erpWareAllocateDetailsVo.setUnitList(erpCommodityUnitMapper.selectErpCommodityUnitList(query));
        }
        return wareAllocateVo;
    }

    /**
     * 查询调拨列表
     *
     * @param erpWareAllocate 调拨
     * @return 调拨
     */
    @Override
    public List<ErpWareAllocateVo> selectErpWareAllocateList(ErpWareAllocate erpWareAllocate) {
        return erpWareAllocateMapper.selectErpWareAllocateList(erpWareAllocate);
    }

    /**
     * 新增调拨
     *
     * @param erpWareAllocate 调拨
     * @return 结果
     */
    @Override
    @Transactional
    public int insertErpWareAllocate(ErpWareAllocateDto erpWareAllocate) {
        erpWareAllocate.setCreateTime(DateUtils.getNowDate());
        erpWareAllocate.setCreateId(SecurityUtils.getUserId());
        erpWareAllocate.setCreateName(SecurityUtils.getUsername());
        erpWareAllocate.setFlag("Y");
        erpWareAllocate.setWareAllocateOdd("DB" + UniqueIdUtils.generateUniqueId());
        erpWareAllocateMapper.insertErpWareAllocate(erpWareAllocate);
        if (erpWareAllocate.getDetailsList() != null && !erpWareAllocate.getDetailsList().isEmpty()) {
            erpWareAllocate.getDetailsList().forEach(item -> {
                item.setWareAllocateId(erpWareAllocate.getWareAllocateId());
            });
            erpWareAllocateMapper.batchInsertWareAllocateDetails(erpWareAllocate.getDetailsList());
        }
        return 1;
    }

    /**
     * 修改调拨
     *
     * @param erpWareAllocate 调拨
     * @return 结果
     */
    @Override
    @Transactional
    public int updateErpWareAllocate(ErpWareAllocateDto erpWareAllocate) {
        erpWareAllocate.setApproveStatus(0);
        erpWareAllocateMapper.updateErpWareAllocate(erpWareAllocate);
        // 先删除库存调拨明细
        erpWareAllocateMapper.deleteWareAllocateDetailsByWareAllocateId(erpWareAllocate.getWareAllocateId());
        if (erpWareAllocate.getDetailsList() != null && !erpWareAllocate.getDetailsList().isEmpty()) {
            erpWareAllocate.getDetailsList().forEach(item -> {
                item.setWareAllocateId(erpWareAllocate.getWareAllocateId());
            });
            erpWareAllocateMapper.batchInsertWareAllocateDetails(erpWareAllocate.getDetailsList());
        }
        return 1;
    }

    /**
     * 批量删除调拨
     *
     * @param wareAllocateIds 需要删除的调拨主键
     * @return 结果
     */
    @Override
    public int deleteErpWareAllocateByWareAllocateIds(Long[] wareAllocateIds) {
        return erpWareAllocateMapper.deleteErpWareAllocateByWareAllocateIds(wareAllocateIds);
    }

    /**
     * 删除调拨信息
     *
     * @param wareAllocateId 调拨主键
     * @return 结果
     */
    @Override
    public int deleteErpWareAllocateByWareAllocateId(Long wareAllocateId) {
        return erpWareAllocateMapper.deleteErpWareAllocateByWareAllocateId(wareAllocateId);
    }

    @Override
    public int auditErpWareAllocate(ErpWareAllocate erpWareAllocate) {
        ErpWareAllocateVo wareAllocate = erpWareAllocateMapper.selectErpWareAllocateByWareAllocateId(erpWareAllocate.getWareAllocateId());
        if (wareAllocate == null) {
            throw new RuntimeException("库存调拨单查询失败");
        }
        wareAllocate.setApproveStatus(erpWareAllocate.getApproveStatus());
        wareAllocate.setApproveName(SecurityUtils.getUsername());
        wareAllocate.setApproveTime(DateUtils.getNowDate());
        if (wareAllocate.getApproveStatus() == 2) {
            wareAllocate.setRejectTime(DateUtils.getNowDate());
            wareAllocate.setRejectReason(erpWareAllocate.getRejectReason());
        }
        // 审核通过时修改库存数量
        if (wareAllocate.getApproveStatus() == 1) {
            // 商品库存信息
            ErpWareCommodityNumber query = new ErpWareCommodityNumber();
            if (wareAllocate.getDetailsList() != null && !wareAllocate.getDetailsList().isEmpty()) {
                wareAllocate.getDetailsList().forEach(item -> {
                    int wareAllocateNumber = 0;
                    // 调拨数量 根据单位乘以调拨数量
                    if (item.getUnitResult() > 0) {
                        wareAllocateNumber = item.getWareAllocateNumber() * item.getUnitResult();
                    } else {
                        wareAllocateNumber = item.getWareAllocateNumber();
                    }
                    // 根据商品id和调出仓库id查询对应库存数据
                    query.setWareId(wareAllocate.getWareOutId());
                    query.setCommodityId(item.getCommodityId());
                    ErpWareCommodityNumber out = erpWareCommodityNumberMapper.selectByCommodityIdAndWareId(query);
                    // 根据调拨数量进行库存相减
                    if (out.getCommodityNumber() < wareAllocateNumber) {
                        throw new RuntimeException("("+item.getCommodityName1()+")仓库库存数量小于调拨数量,调拨单通过失败!");
                    }
                });

                wareAllocate.getDetailsList().forEach(item -> {
                    int wareAllocateNumber = 0;
                    // 调拨数量 根据单位乘以调拨数量
                    if (item.getUnitResult() > 0) {
                        wareAllocateNumber = item.getWareAllocateNumber() * item.getUnitResult();
                    } else {
                        wareAllocateNumber = item.getWareAllocateNumber();
                    }
                    // 根据商品id和调出仓库id查询对应库存数据
                    query.setWareId(wareAllocate.getWareOutId());
                    query.setCommodityId(item.getCommodityId());
                    ErpWareCommodityNumber out = erpWareCommodityNumberMapper.selectByCommodityIdAndWareId(query);
                    out.setCommodityNumber(out.getCommodityNumber() - wareAllocateNumber);
                    erpWareCommodityNumberMapper.updateErpWareCommodityNumber(out);
                    // 新增库存商品变更记录信息
                    ErpCommodityStockAlter erpCommodityStockAlter = StockCommodityAlterUtils.AssemblyInfo(item.getCommodityId(), BigDecimal.valueOf(wareAllocateNumber).negate(), "3", wareAllocate.getWareOutId());
                    erpCommodityStockAlterMapper.insertErpCommodityStockAlter(erpCommodityStockAlter);
                    // 根据商品id和调入仓库id查询对应库存数量
                    query.setWareId(wareAllocate.getWareInId());
                    ErpWareCommodityNumber in = erpWareCommodityNumberMapper.selectByCommodityIdAndWareId(query);
                    if (in == null) {
                        in = new ErpWareCommodityNumber();
                        in.setWareId(wareAllocate.getWareInId());
                        in.setCommodityId(item.getCommodityId());
                        in.setCommodityNumber(wareAllocateNumber);
                        erpWareCommodityNumberMapper.insertErpWareCommodityNumber(in);
                    } else {
                        in.setCommodityNumber(in.getCommodityNumber() + wareAllocateNumber);
                        erpWareCommodityNumberMapper.updateErpWareCommodityNumber(in);
                    }
                    // 新增库存商品变更记录信息
                    erpCommodityStockAlter = StockCommodityAlterUtils.AssemblyInfo(item.getCommodityId(), BigDecimal.valueOf(wareAllocateNumber), "3", wareAllocate.getWareInId());
                    erpCommodityStockAlterMapper.insertErpCommodityStockAlter(erpCommodityStockAlter);
                });
            }
        }
        return erpWareAllocateMapper.updateErpWareAllocate(wareAllocate);
    }
}
